<template>
  <router-view />
</template>

<script setup lang="ts">
import { computed, onMounted } from 'vue'
import { useNow, useIntervalFn } from '@vueuse/core'
import { refreshStockData } from './utils/stock'
import { refreshFundsData } from './utils/fund'
import { useProfitStore } from './stores/profitStore'
import { getAllFunds, getAllStocks } from './data/InvestmentDB'

// 初始化盈亏store
const profitStore = useProfitStore()

// 更新盈亏数据
const updateProfitData = async () => {
  try {
    // 获取最新的基金和股票数据
    const funds = await getAllFunds()
    const stocks = await getAllStocks()

    // 更新store中的盈亏数据
    profitStore.updateFundProfit(funds)
    profitStore.updateStockProfit(stocks)
  } catch (error) {
    console.error('更新盈亏数据失败:', error)
  }
}

// 响应式当前时间（每秒更新）
const now = useNow({ interval: 1000 })

// 响应式判断是否为A股交易时间
const isTradingTime = computed(() => {
  const day = now.value.getDay()
  if (day === 0 || day === 6) return false // 周末

  const hours = now.value.getHours()
  const minutes = now.value.getMinutes()
  const currentTime = hours * 60 + minutes

  const morning = currentTime >= 570 && currentTime <= 690 // 9:30-11:30
  const afternoon = currentTime >= 780 && currentTime <= 900 // 13:00-15:00
  return morning || afternoon
})

// 定时刷新逻辑（依赖交易时间判断）
const { start, stop } = useIntervalFn(
  async () => {
    try {
      if (isTradingTime.value) {
        await refreshStockData() // 仅交易时间刷新A股
        await refreshFundsData()
        await updateProfitData() // 刷新数据后更新盈亏
      }
    } catch (error) {
      console.error('刷新失败:', error)
    }
  },
  5000,
  { immediate: true },
) // 立即执行，每5秒一次
onMounted(async () => {
  await refreshStockData() // 仅交易时间刷新A股
  await refreshFundsData()
  await updateProfitData() // 初始化时更新盈亏
})
</script>

<style lang="scss" scoped></style>
